package com.xuyiwei.mayi.test;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * Created by xuyiwei on 2019/4/13.
 */
class CyclicBarrierDemoRunnable implements Runnable{
    private CyclicBarrier barrier;
    public void setBarrier(CyclicBarrier barrier) {
        this.barrier = barrier;
    }
    @Override
    public void run() {
        if(barrier!=null){
            System.out.println(Thread.currentThread().getName()+"已经开始执行");
            try {
                barrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"已经执行完毕");

        }
    }
}
public class CyclicBarrierDemo {
    public static void main(String[] args) {
        CyclicBarrier barrier = new CyclicBarrier(5);
        CyclicBarrierDemoRunnable runnable = new CyclicBarrierDemoRunnable();
        runnable.setBarrier(barrier);

        for(int i=0;i<5;i++){
            Thread t = new Thread(runnable);
            t.start();
        }
    }
}
